package admin.controllers;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.data.CoordinaData;
import admin.data.DeliveryData;
import admin.data.StoreData;

import models.DeliveryModel;
import models.StoreModel;


public class DeliverySalaryServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		
		TreeMap<String, DeliveryModel> listDelivery = new TreeMap<String, DeliveryModel>();
		request.setAttribute("listDelivery", listDelivery);

		try {
			request.getRequestDispatcher("/admin/pages/delivery_salary.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		String strStartTime = (String) request.getParameter("startTime");
		String strEndTime = (String) request.getParameter("endTime");
		Date startTime;
		Date endTime;
		DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		try {
			startTime = formatter.parse(strStartTime);
			request.setAttribute("startTime", strStartTime);
		} catch (Exception e) {
			startTime = null;
		}
		try {
			endTime = formatter.parse(strEndTime);
			request.setAttribute("endTime", strEndTime);
		} catch (Exception e) {
			endTime = null;
		}
		
		DeliveryData deliveryData = new DeliveryData();
		ArrayList<DeliveryModel> list = deliveryData.getList(startTime, endTime);
		
		TreeMap<String, DeliveryModel> listDelivery = new TreeMap<String, DeliveryModel>();

		for (int i = 0; i < list.size(); i++) {
			DeliveryModel deliveryModel = list.get(i);
			if (listDelivery.containsKey(deliveryModel.getEmployeeId())) {
				int address = deliveryModel.getAddress() + listDelivery.get(deliveryModel.getEmployeeId()).getAddress();
				int order = deliveryModel.getOrder() + listDelivery.get(deliveryModel.getEmployeeId()).getOrder();
				deliveryModel.setAddress(address);
				deliveryModel.setOrder(order);
			} else {
				listDelivery.put(deliveryModel.getEmployeeId(), deliveryModel);
			}
		}
		
		request.setAttribute("listDelivery", listDelivery);

		try {
			request.getRequestDispatcher("/admin/pages/delivery_salary.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}